package equipeAgentes;

import java.awt.Color;
import java.io.IOException;

import robocode.ScannedRobotEvent;
import robocode.TeamRobot;
import static robocode.util.Utils.normalRelativeAngleDegrees;

public class Leader extends TeamRobot {

	static int corner = 0; // Which corner we are currently using
	// static so that it keeps it between rounds.
	boolean stopWhenSeeRobot = false; // See goCorner()

	public void run() {

		setColors(new Color(90, 55, 55), Color.white, Color.blue);

		goCorner();

		// Initialize gun turn speed to 3
		int gunIncrement = 3;

		// Spin gun back and forth
		while (true) {
			for (int i = 0; i < 30; i++) {
				turnGunLeft(gunIncrement);
			}
			gunIncrement *= -1;
		}

	}

	public void onScannedRobot(ScannedRobotEvent event) {

		if (isTeammate(event.getName())) {
			return;
		}



		String name = event.getName();
		double energy = event.getEnergy();

		// Calculate enemy bearing
		double enemyBearing = this.getHeading() + event.getBearing();
		// Calculate enemy's position
		double x = getX() + event.getDistance() * Math.sin(Math.toRadians(enemyBearing));
		double y = getY() + event.getDistance() * Math.cos(Math.toRadians(enemyBearing));

		try {
			// Send enemy position to teammates
			broadcastMessage(new TeamMessage(x, y, energy, name, false));
		} catch (IOException ex) {
			out.println("Unable to send order: ");
			ex.printStackTrace(out);
		}

		if (stopWhenSeeRobot) {
			stop();
			fire(1.0);
			scan();
			// We won't get here if we saw another robot.
			// Okay, we didn't see another robot... start moving or turning again.
			resume();			
		}

	}

	public void goCorner() {
		// We don't want to stop when we're just turning...
		stopWhenSeeRobot = false;
		// turn to face the wall to the "right" of our desired corner.
		turnRight(normalRelativeAngleDegrees(corner - getHeading()));
		// Ok, now we don't want to crash into any robot in our way...
		stopWhenSeeRobot = true;
		// Move to that wall
		ahead(5000);
		// Turn to face the corner
		turnLeft(90);
		// Move to the corner
		ahead(5000);
		// Turn gun to starting point
		turnGunLeft(90);
	}

}
